package com.ruoyi.spider.spiderConfig.handle;

import cn.hutool.core.lang.ObjectId;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.oss.cloud.CloudConstant;
import com.ruoyi.oss.cloud.CloudStorageConfig;
import com.ruoyi.oss.cloud.CloudStorageService;
import com.ruoyi.oss.cloud.OSSFactory;
import com.ruoyi.oss.service.ISysOssService;
import com.ruoyi.spider.domain.SpiderArticle;
import com.ruoyi.spider.util.ImgStrUtils;
import com.ruoyi.spider.util.SpiderImgUtil;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.ByteArrayInputStream;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xgt(小光头)
 * @version 1.0
 * @date 2021-1-17 15:03
 */
public class Imghandle implements handle {


    private static ISysOssService sysOssService;

    private static ISysConfigService sysConfigService;

    static
    {
        sysConfigService = (ISysConfigService) SpringUtils.getBean(ISysConfigService.class);
        sysOssService = (ISysOssService) SpringUtils.getBean(ISysOssService.class);
    }


    @Override
    public Object process(Object object) {


        JSONObject jsonObject = JSONObject.parseObject(object.toString());
        Map<String,Object> spiderMap = (Map<String,Object>)jsonObject;


        //将内容中的图片替换掉
        CloudStorageService storage = OSSFactory.build();
        // 获取云存储配置信息
        String jsonconfig = sysConfigService.selectConfigByKey(CloudConstant.CLOUD_STORAGE_CONFIG_KEY);
        CloudStorageConfig config = JSON.parseObject(jsonconfig, CloudStorageConfig.class);
        String content = spiderMap.get("content").toString();
        //读取html中的图片
        List<String> imageList = SpiderImgUtil.getImgSrcXD(content);

        for (String imgUrl : imageList) {
            //判断是不是已经是服务器的图片
            if(!imgUrl.contains("xianbaovip.com")){
                //将图片地址转成了流
                //String key = null;
                byte[] uploadBytes = ImgStrUtils.doGetRequestForFile(imgUrl);
                if(uploadBytes==null){
                    return  "";
                }
                ByteArrayInputStream byteInputStream=new ByteArrayInputStream(uploadBytes);

                String realUrl = storage.uploadSuffix(byteInputStream,"/" + config.getQiniuBucketImgStyleSuffix());

                //将文中的链接替换掉
                content = StrUtil.replace(content, StrUtil.removeAll(imgUrl,"https://www.x6d.com"), realUrl, true);
            }
        }
        spiderMap.put("content", content);
        spiderMap.put("fristimg", SpiderImgUtil.getImgOneSrc(content));




        return spiderMap;
    }
}
